package com.xja.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.xja.entity.Bookinfo;
import com.xja.entity.Orderinfo;
import com.xja.entity.PageResult;
import com.xja.entity.Userinfo;
import com.xja.feignclient.OrderService;
import com.xja.service.BookinfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.awt.print.Book;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 周广瑞
 * @date 2022/4/26 11:31
 */
@RestController
@RequestMapping("book")
//@CrossOrigin(allowCredentials = "true")
public class BookController {
    private Logger logger= LoggerFactory.getLogger(BookController.class);
    @Autowired
    private BookinfoService bookinfoService;
//timeSentinel
    @Autowired
    private OrderService orderService;
    @RequestMapping("find")
    public PageResult<List<Bookinfo>>findall(){
            logger.info("调用了图书业务查询所有的图书功能");
        List<Bookinfo> bookinfoList = bookinfoService.slectBook();
        return PageResult.success("成功",bookinfoList);
    }

    @RequestMapping("testSentinel")
    @SentinelResource(value = "testSentinel_rule", blockHandler = "testSentinelMethod")
    public String testSentinel() {
        logger.info("调用了测试的方法");
        return "成功";
    }
    public String testSentinelMethod(BlockException blockException) {
        logger.info("调用了限流规则");
        return "访问频率太快，请稍后访问";
    }
//       @RequestMapping("find")
//    public PageResult<List<Bookinfo>>findall(){
//        Entry entry=null;
//            try {
//        entry= SphU.entry("find_rule");
//            List<Bookinfo> bookinfoList = bookinfoService.slectBook();
//        return PageResult.success("成功",bookinfoList);
//    } catch (Exception e) {
//        System.out.println("超出了限制");
//        e.printStackTrace();
//    }finally {
//        if (entry!=null){
//            entry.exit();;
//        }
//    }
//        return PageResult.error("点击太快骚等片刻",null);
//}


    @RequestMapping("findone")
    @SentinelResource(value = "find_rule",blockHandler = "findoneSentinel")
    public PageResult<List<Bookinfo>> findone(@RequestParam("bid")Integer bid){
        logger.info("调用了图书业务中查询所有图书的功能");
        Bookinfo bookinfo = bookinfoService.selectByPrimaryKey(bid);
        return PageResult.success("成功",bookinfo);
    }
    public PageResult<Bookinfo>findoneSentinel(@RequestParam("bid")Integer bid, BlockException blockException){
           return PageResult.error("访问过大骚等。。。。",null);
    }



    @RequestMapping("findall")
    public PageResult<List<Bookinfo>> findallweb(){
        logger.info("调用了图书业务中查询所有图书的功能");
        List<Bookinfo> bookinfoList =bookinfoService.slectBook();
        for(Bookinfo bookinfo1:bookinfoList){
            System.out.println("bookinfo1 = " + bookinfo1);
        }
        return PageResult.success("成功",bookinfoList);
    }

    @RequestMapping("findbid")
    public PageResult<Map<String,Object>>FindBid(@RequestParam("bid") Integer bid){
        logger.info("显示图书订单信息以及图书信息");

         Bookinfo book = bookinfoService.selectByPrimaryKey(bid);
        if (book ==null)
            return PageResult.nullresult("图书不存在",null);

        PageResult<List<Orderinfo>> pageResult = orderService.FinBid(book.getBid());

        List<Orderinfo> orderinfoList = pageResult.getObj();
        Map<String,Object>userMap = new HashMap<>();
        userMap.put("book",book);
        userMap.put("orderinfoList",orderinfoList);

        return PageResult.success("成功",userMap);
    }

    //按照用户id 查询用户信息
    @RequestMapping("findbookbybid")
    public PageResult<Bookinfo>findBookByBid(@RequestParam("bid")Integer bid){
        logger.info("调用了订单业务查询所有的信息");
        Bookinfo book = bookinfoService.selectByPrimaryKey(bid);
        return PageResult.success("成功",book);

    }

    //  定制限流规则
    @RequestMapping("initsentenlrule")
    public String InitSentenlRule(){
        ArrayList<FlowRule> roleList = new ArrayList<>();
        //单个规则
        FlowRule flowRule = new FlowRule();
        flowRule.setCount(1);//一次访问限定
        flowRule.setResource("find_rule");//定义规则名称
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setLimitApp("default");
        roleList.add(flowRule);
        //定义单个的规则
        FlowRule flowRule1 = new FlowRule();
        flowRule1.setCount(2);//一次访问限定
        flowRule1.setResource("find_rule");//定义规则名称
        flowRule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule1.setLimitApp("default");
        roleList.add(flowRule1);
        FlowRuleManager.loadRules(roleList);
        return "限流成功。。。。。。。";
    }


    @SentinelResource(value = "BookDownByTime",fallback = "downFallback")
    @RequestMapping("/BookDownByTime")
    public String BookDownByTime(){
        try {
            Thread.sleep(300);
        }catch (Exception exception){

        }
        return "根据平均时间降级";
    }

    public String downFallback(){
        return "服务器降级了。。。。。。。。。。。。。。。当前请求过多  骚等。";
    }


    @RequestMapping("findallSentinel")
    @SentinelResource(value = "mdy", blockHandler = "findallSentinel")
    public PageResult<List<Bookinfo>> mdy(HttpServletRequest request){
        logger.info("调用了用户业务中查询所有用户的功能");
//        int random=(int)(Math.random()*200)>1000?1:0;
        int random=(int)(Math.random()*3);
        System.out.println(random);
        int resu =23/random;
        List<Bookinfo> userinfoList =bookinfoService.slectBook();
        return PageResult.success("成功",userinfoList);
    }
    public PageResult<List<Bookinfo>> findallSentinel(HttpServletRequest request){
        return PageResult.error("20秒之后访问",null);
    }

    @PostMapping("add")
    public PageResult<Map<String,Object>> add(Bookinfo bookinfo){
        logger.info("添加图书功能");
//        int random=(int)(Math.random()*200)>1000?1:0;
       bookinfo.setBid((int)(Math.random()*8999));

      bookinfoService.insert(bookinfo);
        return PageResult.success("成功",null);
    }

}
